<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['nmy:transaction:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['nmy:transaction:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['nmy:transaction:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['nmy:transaction:export']"
          >导出</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
       
          >导入</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="transactionList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="凭证字号" align="center" prop="bh" />
      <el-table-column label="科目名称" align="center" prop="subject" />
      <el-table-column label="创建时间" align="center" prop="cTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.cTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借款金额" align="center" prop="jPrice" />
      <el-table-column label="贷款金额" align="center" prop="dPrice" />

      <el-table-column label="合计" align="center" prop="hj">
        <template #default="scope">
          <span>{{ numberToChineseUppercase(scope.row.jPrice) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <div class="red-stamp" v-if="scope.row.status === 2">
            <span class="stamp-text">已红冲</span>
          </div>
          <el-tag v-if="scope.row.status === 2" type="success">异常</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="shStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.shStatus === 1" type="success">审核通过</el-tag>
          <el-tag v-if="scope.row.shStatus === 2" type="success">审核未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['nmy:transaction:edit']"
            v-if="scope.row.shStatus === 1"
            >红冲</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['nmy:transaction:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />



 <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xlsx、xls格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitFileForm"
            :loading="upload.isUploading"
            >确 定</el-button
          >
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 添加或修改测试红冲列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="transactionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="凭证字号" prop="bh">
          <el-input disabled v-model="form.bh" placeholder="请输入凭证字号" />
        </el-form-item>
        <el-form-item label="科目名称" prop="subject">
          <el-input disabled v-model="form.subject" placeholder="请输入科目名称" />
        </el-form-item>
        <el-form-item label="创建时间" prop="cTime">
          <el-date-picker
            clearable
            v-model="form.cTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="借款金额" prop="jPrice">
          <el-input v-model="form.jPrice" placeholder="请输入借款金额" />
        </el-form-item>
        <el-form-item label="贷款总金额" prop="dPrice">
          <el-input v-model="form.dPrice" placeholder="请输入贷款金额" />
        </el-form-item>

        <!-- 动态贷款金额输入框 -->
        <el-form-item
          v-for="(domain, index) in form.dPriceList"
          :key="index"
          :label="'贷款金额' + (index + 2)"
        >
          <el-input v-model="domain.dPrice" placeholder="请输入贷款金额" />
          <el-button 
            type="danger" 
            link 
            icon="Delete"
            @click="removeDomain(index)"
            style="margin-left: 10px"
          >删除</el-button>
        </el-form-item>
        <el-button @click="addDomain" type="primary" plain>添加贷款金额</el-button>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 修改测试红冲列表对话框 -->
    <el-dialog :title="title" v-model="open1" width="500px" append-to-body>
      <el-form ref="transactionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="凭证字号" prop="bh">
          <el-input disabled v-model="form.bh" placeholder="请输入凭证字号" />
        </el-form-item>
        <el-form-item label="科目名称" prop="subject">
          <el-input disabled v-model="form.subject" placeholder="请输入科目名称" />
        </el-form-item>
        <el-form-item label="创建时间" prop="cTime">
          <el-date-picker
            clearable
            v-model="form.cTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="借款金额" prop="jPrice">
          <el-input v-model="form.jPrice" placeholder="请输入借款金额" />
        </el-form-item>
        <el-form-item label="贷款总金额" prop="dPrice">
          <el-input v-model="form.dPrice" placeholder="请输入贷款金额" />
        </el-form-item>

        <!-- 动态贷款金额输入框 -->
        <el-form-item
          v-for="(domain, index) in form.dPriceList"
          :key="index"
          :label="'贷款金额' + (index + 2)"
        >
          <el-input v-model="domain.dPrice" placeholder="请输入贷款金额" />
          <el-button 
            type="danger" 
            link 
            icon="Delete"
            @click="removeDomain(index)"
            style="margin-left: 10px"
          >删除</el-button>
        </el-form-item>
        <el-button @click="addDomain" type="primary" plain>添加贷款金额</el-button>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Transaction">
import { listTransaction, getTransaction, delTransaction, addTransaction, updateTransaction,getImportTemplate } from "@/api/nmy/transaction";
import { ref, watch } from "vue";

const { proxy } = getCurrentInstance();

const transactionList = ref([]);
const open = ref(false);
const open1 = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    id: null,
    name: null,
    bh: null,
    subject: null,
    cTime: null,
    jPrice: null,
    dPrice: null,
    dPriceList: [], // 确保初始化为空数组
    hj: null,
    status: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    id: [
      { required: true, message: "ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    bh: [
      { required: true, message: "凭证字号不能为空", trigger: "blur" }
    ],
    subject: [
      { required: true, message: "科目名称不能为空", trigger: "blur" }
    ],
    cTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    jPrice: [
      { required: true, message: "借款金额不能为空", trigger: "blur" }
    ],
    dPrice: [
      { required: true, message: "贷款金额不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);



// 导入参数
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  fileList: [], // 添加文件列表存储
});

// 文件上传ref
const uploadRef = ref(null);

/** 导入按钮操作 */
function handleImport() {
  upload.title = "五险一金数据导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  console.log("导入模板");
  getImportTemplate().then((res) => {
    const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "五险一金导入模板.xlsx";
    link.click();
    window.URL.revokeObjectURL(link.href);
  });
}

// 文件状态改变
function handleFileChange(file) {
  upload.fileList = [file];
}

// 文件移除
function handleFileRemove() {
  upload.fileList = [];
}

// 提交上传文件
function submitFileForm() {
  if (!upload.fileList.length) {
    proxy.$modal.msgError("请选择要上传的文件");
    return;
  }
  const formData = new FormData();
  formData.append("file", upload.fileList[0].raw);
  upload.isUploading = true;
  importSocialsecurity(formData)
    .then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.msg);
        upload.open = false;
        getList();
      } else {
        proxy.$modal.msgError(res.msg);
      }
      upload.isUploading = false;
      upload.fileList = [];
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    })
    .catch(() => {
      upload.isUploading = false;
    });
}







/** 查询测试红冲列表列表 */
function getList() {
  loading.value = true;
  listTransaction(queryParams.value).then(response => {
    transactionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  open1.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    bh: null,
    subject: null,
    cTime: null,
    jPrice: null,
    dPrice: null,
    dPriceList: [], // 重置时清空贷款金额列表
    hj: null,
    status: null
  };
  proxy.resetForm("transactionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加测试红冲列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  if(row.status === 2){
    proxy.$modal.confirm('是否再次红冲编号为"' + row.id + '"的数据项？').then(function() {
    reset();
    const _id = row.id || ids.value
    getTransaction(_id).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改测试红冲列表";
    });
    });
  }else{
    reset();
    const _id = row.id || ids.value
    getTransaction(_id).then(response => {
      form.value = response.data;
      open1.value = true;
      title.value = "修改测试红冲列表";
    });
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["transactionRef"].validate(valid => {
    if (valid) {
      // 计算动态贷款金额的总和
      let dynamicTotal = 0;
      if (form.value.dPriceList && form.value.dPriceList.length > 0) {
        form.value.dPriceList.forEach(item => {
          dynamicTotal += Number(item.dPrice || 0);
        });
      }

      // 获取主贷款金额
      const mainDPrice = Number(form.value.dPrice || 0);
      
      // 如果主贷款金额为0，则使用动态贷款金额之和
      const totalDPrice = mainDPrice > 0 ? mainDPrice : dynamicTotal;

      // 检查借方金额是否等于贷方金额
      if (Number(form.value.jPrice) !== totalDPrice) {
        proxy.$modal.msgError("借贷不平衡！借方金额必须等于贷方金额！");
        return;
      }

      if (form.value.id != null) {
        updateTransaction(form.value).then(response => {
          proxy.$modal.msgSuccess("红冲成功");
          // 根据当前打开的是哪个对话框来关闭
          if (open.value) {
            open.value = false;
          }
          if (open1.value) {
            open1.value = false;
          }
          getList();
        });
      } else {
        addTransaction(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除测试红冲列表编号为"' + _ids + '"的数据项？').then(function() {
    return delTransaction(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('nmy/transaction/export', {
    ...queryParams.value
  }, `transaction_${new Date().getTime()}.xlsx`)
}

function numberToChineseUppercase(num) {
  const units = ['', '拾', '佰', '仟'];
  const chars = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const bigUnits = ['', '万', '亿'];
  const decimalUnits = ['角', '分']; // 小数单位

  if (num === 0) return chars[0] + '元整'; // 如果是 0，返回 "零元整"

  let isNegative = false;
  if (num < 0) {
    isNegative = true; // 标记为负数
    num = Math.abs(num); // 取绝对值
  }

  // 处理整数部分
  let integerPart = Math.floor(num); // 整数部分
  let decimalPart = Math.round((num - integerPart) * 100); // 小数部分，保留两位

  let result = '';

  // 转换整数部分
  if (integerPart > 0) {
    let unitIndex = 0;
    let zeroFlag = false;

    while (integerPart > 0) {
      let segment = integerPart % 10000; // 每次处理 4 位（个、十、百、千）
      if (segment === 0) {
        zeroFlag = true; // 如果当前段为 0，标记为零
      } else {
        if (zeroFlag) {
          result = chars[0] + result; // 如果之前有零，补一个 "零"
          zeroFlag = false;
        }
        let segmentStr = '';
        let tempSegment = segment; // 临时变量，用于处理 segment
        for (let i = 0; i < String(segment).length; i++) {
          const digit = tempSegment % 10;
          if (digit !== 0) {
            segmentStr = chars[digit] + units[i] + segmentStr;
          } else {
            if (segmentStr.charAt(0) !== chars[0]) {
              segmentStr = chars[0] + segmentStr;
            }
          }
          tempSegment = Math.floor(tempSegment / 10); // 修改 tempSegment 的值
        }
        result = segmentStr + bigUnits[unitIndex] + result;
      }
      integerPart = Math.floor(integerPart / 10000);
      unitIndex++;
    }

    // 处理多余的 "零"
    result = result.replace(/零+/g, '零').replace(/零$/, '');
    result += '元'; // 添加 "元"
  } else {
    result += '零元'; // 如果整数部分为 0，添加 "零元"
  }

  // 转换小数部分
  if (decimalPart > 0) {
    let decimalStr = '';
    for (let i = 0; i < decimalUnits.length; i++) {
      const digit = Math.floor(decimalPart / Math.pow(10, decimalUnits.length - 1 - i)) % 10;
      if (digit !== 0) {
        decimalStr += chars[digit] + decimalUnits[i];
      }
    }
    result += decimalStr;
  } else {
    result += '整'; // 如果小数部分为 0，添加 "整"
  }

  // 如果是负数，添加 "负" 前缀
  if (isNegative) {
    result = '负' + result;
  }

  return result;
}

// 修改 addDomain 函数
function addDomain() {
  if (!form.value.dPriceList) {
    form.value.dPriceList = [];
  }
  form.value.dPriceList.push({
    dPrice: '0'
  });
}

// 删除贷款金额输入框
function removeDomain(index) {
  form.value.dPriceList.splice(index, 1);
}

// 添加监听器，监听动态贷款金额的变化
watch(
  () => form.value.dPriceList,
  (newList) => {
    if (newList && newList.length > 0) {
      // 计算动态贷款金额的总和
      let totalDPrice = 0;
      newList.forEach(item => {
        totalDPrice += Number(item.dPrice || 0);
      });
      // 更新主贷款金额
      form.value.dPrice = totalDPrice.toString();
    }
  },
  {
    deep: true, // 深度监听数组变化
    immediate: true // 立即执行一次
  }
);

getList();
</script>
<style scoped>
.red-stamp {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 0, 0, 0.1);
  border: 2px solid red;
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 16px;
  font-weight: normal;
  color: red;
  text-transform: uppercase;
}
</style>
